package com.dorne.spring.filter;

import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Slf4j
public class ResponseLogGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            HttpStatusCode statusCode = originalResponse.getStatusCode();
            if (statusCode != HttpStatus.OK) {
                return chain.filter(exchange);//降级处理返回数据
            }
            ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                @Override
                public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                    if (body instanceof Flux) {
                        Flux<? extends DataBuffer> fluxBody = Flux.from(body);

                        return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                            return printBody(dataBuffers, bufferFactory, this);
                        }));
                    }
                    return super.writeWith(body);
                }

                @Override
                public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {
                    return super.writeAndFlushWith(Flux.from(body).map(inner -> {
                        if (inner instanceof Flux) {
                            return ((Flux<? extends DataBuffer>) inner)
                                    .buffer()
                                    .map(dataBuffers -> printBody(dataBuffers, bufferFactory, this));
                        } else {
                            log.warn("Non-Flux inner body detected: {}", inner.getClass().getName());
                            return inner;
                        }
                    }));
                }
            };
            return chain.filter(exchange.mutate().response(decoratedResponse).build());

        } catch (Exception e) {
            log.error("gateway log exception.\n" + e);
            return chain.filter(exchange);
        }
    }

    private DataBuffer printBody(List<? extends DataBuffer> dataBuffers,
                           DataBufferFactory bufferFactory,
                           ServerHttpResponseDecorator decoratedResponse){
        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
        DataBuffer buff = dataBufferFactory.join(dataBuffers);
        byte[] content = new byte[buff.readableByteCount()];
        buff.read(content);
        DataBufferUtils.release(buff);//释放掉内存
        // 构建返回日志
        String result = new String(content);
        log.info("<-- 响应体信息 --> {}", result);
        return bufferFactory.wrap(result.getBytes());
    }


    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
